<?php
/* --------------------------------------------------------------
   ShowLogs.php 2011-03-01 gm
   Gambio GmbH
   http://www.gambio.de
   Copyright (c) 2011 Gambio GmbH
   Released under the GNU General Public License (Version 2)
   [http://www.gnu.org/licenses/gpl-2.0.html]
   --------------------------------------------------------------
*/

class ShowLogs
{
    /*
     * path to the logfiles
     */
    var $v_path = '';
    
    /*
     * constructor
     */
    function ShowLogs()
    {
		$this->v_path = DIR_FS_CATALOG . 'logfiles/';
    }

    /*
     * determined number of pages of logfiles
     *
     * @param string $p_file Filename with path
     * @param int $p_num_value Offset value
     * @return array Array with page numbers and ID
     */
    function get_page_number($p_file, $p_num_value = 150)
    {
        $t_result_array[0]['id'] = 1;
        $t_result_array[0]['text'] = 1;
        
        $t_is_file = is_file($this->v_path.$p_file);
        if(!$t_is_file) {
            return $t_result_array;
        }

        $p_filesize = filesize($this->v_path.$p_file);
        if(!$p_filesize) {
            return $t_result_array;
        }
        
        $t_offset = ($p_num_value * 120);
        $t_page_number = ceil(($p_filesize / $t_offset));

        $t_result_array = array();
        $b = $t_page_number;
        for($i = 1; $i <= $t_page_number; $i++) {
            $t_result_array[$i]['id'] = $b;
            $t_result_array[$i]['text'] = $i;
            $b--;
        }
        return ($t_result_array);
    }

    /*
     * read part of the selected logfile
     *
     * @param string $p_file Filename with path
     * @param int $p_page Page number
     * @param int $p_num_value Offset number
     * @return string Part of the logfile
     */
    function get_log($p_file, $p_page, $p_num_value = 150)
    {
		$t_buffer = '';

        $t_is_file = is_file($this->v_path.$p_file);
        if(!$t_is_file) {
            return $t_buffer;
        }
		
		$t_file = $p_file;
		
		if(strpos($t_file, '.log.gz') !== false)
		{
			$t_handle = gzopen($this->v_path . $t_file, 'r');
			$t_gz_content = '';
			while(!feof($t_handle))
			{
			  $t_gz_content .= gzread($t_handle, 10000);			 			  
			}
			gzclose($t_handle);
				
			$t_file .= '.temp';
			
			$t_handle = fopen($this->v_path . $t_file, 'w+');
			fwrite($t_handle, $t_gz_content);
			fclose($t_handle);
			
		}

        $t_handle = fopen($this->v_path.$t_file, "r");
        if(!$t_handle) {
            return $t_buffer;
        }

        $t_offset = (-$p_num_value * 120) * $p_page;
        $t_offset_plus = (($p_num_value+2) * 120);

        // go to end of file an return to t_offset
        fseek($t_handle, $t_offset, SEEK_END);
        // get the position
        $t_position = ftell($t_handle);
        // read the file
        $t_buffer = fread($t_handle, $t_offset_plus);

        // cut the first line if position not the first line
        if($t_position > 0) {
            $t_buffer = substr($t_buffer, (strpos($t_buffer, "\n")+1));
        }
        // cut the last line
        $t_buffer = substr($t_buffer, 0, strrpos($t_buffer, "\n"));

        fclose($t_handle);

		// highlight log
		$t_buffer = $this->color_log($t_file, $t_buffer);

 		// Image Processing
		if(strstr($t_file, 'debug-image_processing')) {
			$string = '#ERROR#';
			$t_buffer = str_replace($string, '<span style="color: red;">'.$string.'</span>', $t_buffer);
		}

		if(substr($t_file, -5) == '.temp')
		{
			unlink($this->v_path.$t_file);
		}

        return $t_buffer;
    }

    /*
     * scan directory for logfiles
     *
     * @result array Array with logfiles
     */
    function scan_dir()
    {
        $t_result_array[0]['id'] = '';
        $t_result_array[0]['text'] = TEXT_INFO_NO_FILES;

        $t_is_dir = is_dir($this->v_path);
        if(!$t_is_dir) {
            return $t_result_array;
        }
        $t_dh = opendir($this->v_path);
        if(!$t_dh) {
            return $t_result_array;
        }

        $t_result_array = array();
        $i = 0;
        while (($t_file = readdir($t_dh)) !== false) {
            // just get *.log files
            if ($t_file != "." && $t_file != ".." && !is_dir($t_file) && strstr($t_file, ".log")) {
                $t_result_array[$i]['id'] = urlencode($t_file);
                $t_result_array[$i]['text'] = '['.date ("d.m.Y", filemtime($this->v_path.$t_file)).'] '.$t_file;
                $i++;
				clearstatcache();
            }
        }
		asort($t_result_array);
        return $t_result_array;
    }

    /*
     * check the filename
     *
     * @param string $p_file File from GET
     * @param array $p_file_array Array with logfiles from the directory
     * @return bool true:ok | false:if incorect filename
     */
    function check_file_name($p_file, $p_file_array)
    {
        foreach($p_file_array as $file) {
            if($file['id'] == $p_file) {
                return true;
            }
        }
        return false;
    }

	function clear_log($p_filename)
	{
		$t_file = $this->v_path.$p_filename;
		if(file_exists($t_file)) {
			$t_handle = fopen($t_file, 'w+');
			ftruncate($t_handle, 0);
			fclose($t_handle);
			echo 'Log geleert.';
			return;
		}
		echo 'Log nicht vorhanden.';
	}

	function delete_log($p_filename)
	{
		$t_file = $this->v_path.$p_filename;
		if(file_exists($t_file)) {
			unlink($t_file);
			echo 'Log gel&ouml;scht.';
			return;
		}
		echo 'Log nicht gel&ouml;scht.';
	}

	function color_log($p_log_name, $p_buffer)
	{
		$t_buffer = $p_buffer;
		// Paypal Log ----------------------------------------------------------
		if(strstr($p_log_name, 'payment.paypal_api_calls')) {
			$teiler = "\n".'<div>================================================================================</div>';
			// Parameter umbrechen
			$p_buffer = str_replace('&', "\n", $p_buffer);
			// Text Highlighten
			$p_buffer = str_replace('| RESPONSE:', '<div style="color: blue;">RESPONSE:</div>', $p_buffer);
			$p_buffer = str_replace('| STREAM', '<div style="color: blue;">STREAM RESPONSE:</div>', $p_buffer);
			$p_buffer = str_replace("\n".'ACK=Failure', "\n".'<span style="color: red;">ACK=Failure</span>', $p_buffer);
			$p_buffer = str_replace("\n".'ACK=Success', "\n".'<span style="color: green;">ACK=Success</span>', $p_buffer);
			// Datum
			$suchmuster = '/(\d{2}).(\d{2}).(\d{4}) (\d{2}):(\d{2})/i';
			$ersetzung = $teiler.'<div style="color: gray;">$1.$2.$3 $4:$5</div>';
			$p_buffer = preg_replace($suchmuster, $ersetzung, $p_buffer);
			// Methode
			$suchmuster = '/(METHOD=)(\w+)/i';
			$ersetzung = "\n".'<span style="color: white; background-color: blue;">$1$2</span>';
			$p_buffer = preg_replace($suchmuster, $ersetzung, $p_buffer);
		}
		// PayPal Antwort
		if(strstr($p_log_name, 'payment.paypal_ipn')) {
			$p_buffer = str_replace('|', "\n", $p_buffer);
			$p_buffer = str_replace('RESPONSE', '<span style="color: green;">RESPONSE</span>', $p_buffer);
			$suchmuster = '/(\d{2}).(\d{2}).(\d{4}) (\d{2}):(\d{2})/i';
			$ersetzung = "\n".'<span style="color: red;">$1.$2.$3 $4:$5</span>';
			$p_buffer = preg_replace($suchmuster, $ersetzung, $p_buffer);
		}

		return urldecode($p_buffer);
	}
}
?>